package com.hao.thread;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 有返回值的多线程
 *
 * @author haohj
 * @date 2020-04-28 14:47
 */
public class Demo3 {
    public static void main(String[] args) {
        System.out.println("-----程序开始运行------");
        LocalDateTime startTime = LocalDateTime.now();

        int taskSize = 5;

        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(taskSize);

        // 创建多个有返回值的任务
        List<Future> futureList = new ArrayList<>();
        for (int i = 0; i < taskSize; i++) {
            Callable c = new MyCallable(i + " ");
            // 执行任务并获取Future对象
            Future future = executorService.submit(c);
            futureList.add(future);
        }

        // 关闭线程池
        executorService.shutdown();

        // 获取所有并发任务的运行结果
        futureList.forEach(future -> {
            try {
                System.out.println(">>>" + future.get().toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime,endTime);
        System.out.println("----程序结束运行----，程序运行时间【"
                + duration.toMillis() + "毫秒】");
    }

    public static class MyCallable implements Callable<Object> {
        private String taskNum;

        public MyCallable(String taskNum) {
            this.taskNum = taskNum;
        }

        @Override
        public Object call() throws Exception {
            System.out.println(">>>" + taskNum + "任务启动");
            LocalDateTime dateTmp1 = LocalDateTime.now();
            Thread.sleep(1000);
            LocalDateTime dateTmp2 = LocalDateTime.now();
            Duration duration = Duration.between(dateTmp1,dateTmp2);
            System.out.println(">>>" + taskNum + "任务终止");
            return taskNum + "任务返回运行结果,当前任务时间【" + duration.toMillis() + "毫秒】";
        }
    }
}
